import sys

file_path = sys.argv[1]


def find_text_in_file(text, afile):
	with open(afile, 'r') as f:
		lines = f.readlines()
	target_idex = 0
	for idex, line in enumerate(lines):
		if text in line:
			target_idex = idex
			break
	return target_idex

def insert_text_in_file(text, idex, afile):
	with open(afile, 'r') as f:
		lines = f.readlines()

	lines.insert(idex+1, text+"\n")
	with open(afile, 'w') as f:
		f.writelines(lines)


def edit_text(keys, turple_xy, layer, ori):
	x1 = turple_xy[0]
	y1 = turple_xy[1]
	x2 = turple_xy[2]
	y2 = turple_xy[3]

	target_text = ""
	for key in keys :
		target_text += "  PIN "+key+"\n"
		target_text += "    DIRECTION INPUT ;\n"
		target_text += "    USE SIGNAL ;\n"
		target_text += "    PORT\n"
		target_text += "      LAYER "+layer+" ;\n"
		if ori == "H":
			y1 -= 0.32
			y2 -= 0.32
			target_text += "        RECT {} {} {} {} ;\n".format(str(round(x1, 3)), str(round(y1, 3)), str(round(x2, 3)), str(round(y2, 3)))
		if ori == "V":
			x1 += 0.32
			x2 += 0.32
			target_text += "        RECT {} {} {} {} ;\n".format(str(round(x1, 3)), str(round(y1, 3)), str(round(x2, 3)), str(round(y2, 3)))
		target_text += "    END\n"
		target_text += "  END "+key+"\n"
	return target_text

def del_text(keys, afile):
	with open(afile, 'r') as f:
		lines = f.readlines()

	for key in keys:
		print("delete "+key)
		with open(afile, 'r') as f:
			lines = f.readlines()
		begin_line = find_text_in_file("PIN "+key, afile)
		end_line = find_text_in_file("END "+key, afile)
		print((begin_line, end_line))
		del lines[begin_line:end_line+1]
	
		with open(afile, 'w') as f:
			f.writelines(lines)
		
	


keys = []

find_key = "SYMMETRY X Y"

keys_1 = keys[:1288]
keys_2 = keys[1288:]

#context = edit_text(keys, (0.0, 700.88, 0.16, 701.04), "M9", "V")
#context = edit_text(keys, (700.94, 41.84, 701.1, 42.0), "M8", "H")
context_1 = edit_text(keys_1, (566.12, 700.84, 566.28, 701.0), "M8", "H")
context_2 = edit_text(keys_2, (566.12, 700.68, 566.28, 700.84), "M6", "H")

#context_1 = edit_text(keys_1, (0.0, 700.88, 0.16, 701.04), "M9", "V")
#context_2 = edit_text(keys_2, (0.16, 700.88, 0.32, 701.04), "M7", "V")

#find_key = "SITE CoreSite"
#context = edit_text(keys, (0.0, 11.84, 0.16, 12.0), "M9", "V")
a = find_text_in_file(find_key, file_path)
insert_text_in_file(context_1, a, file_path)
a = find_text_in_file(find_key, file_path)
insert_text_in_file(context_2, a, file_path)


#del_keys = ['AUX_EN', 'DIFF_EN', 'DLPBK', 'DVDD', 'RCV_MODE0', 'RCV_MODE1', 'RCV_SEL']

#del_text(del_keys, file_path)